package com.zeldu.chat.server;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zeldu.chat.config.RedisConfig;
import com.zeldu.chat.pojo.RequestMessage;
import com.zeldu.chat.pojo.ResponseMessage;
import com.zeldu.chat.service.ChatService;
import com.zeldu.chat.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/{jsondata}")
public class ChatServer {

    private static Map<String, Map<String, Session>> allClients = new ConcurrentHashMap<>();
    private static ApplicationContext applicationContext;
    private String courseId = "null";
    private String userId = "null";

    @Autowired
    public static void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("jsondata") String jsondata) {

        try {
            jsondata = URLDecoder.decode(jsondata, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        RedisUtil redisUtil = applicationContext.getBean(RedisUtil.class);
        String courseId, userId, userName;
        jsondata = "{" + jsondata + "}";
        JSONObject jsonObject = JSON.parseObject(jsondata);
        courseId = jsonObject.getString("courseId");
        userId = jsonObject.getString("userId");
        userName = jsonObject.getString("name");
        //存储客户端链接
        Map<String, Session> courseClients = null;
        try {
            //courseClients =allClients.get(courseId);
            courseClients = allClients.get(courseId);
            courseClients.put(userId, session);
        } catch (NullPointerException e) {
            e.printStackTrace();
            courseClients = new ConcurrentHashMap<>();
            courseClients.put(userId, session);
        }

        allClients.put(courseId, courseClients);
        redisUtil.hset(courseId, userId, userName);
        System.out.println(courseId + ":" + userId + ":" + userName + ":加入连接");
        this.courseId = courseId;
        this.userId = userId;
        sendCount();

//        ChatService cs=applicationContext.getBean(ChatService.class);
////
//        String[] data = cs.open(session, jsondata);
//        this.courseId = data[0];
//        this.userId = data[1];

    }

    @OnClose
    public void onClose() {
//        ChatService cs=applicationContext.getBean(ChatService.class);
//        cs.close(courseId, userId);
        try {
            RedisUtil redisUtil = applicationContext.getBean(RedisUtil.class);
            redisUtil.hdel(courseId, userId);
            allClients.get(courseId).remove(userId);
            System.out.println(courseId + ":" + userId + ":断开连接");
        } catch (NullPointerException e) {
            System.out.println(e);
            System.out.println("前端请求数据格式错误，无法连接");
        }

    }

    @OnMessage
    public void onMessage(String message) {
//        ChatService cs=applicationContext.getBean(ChatService.class);
//        cs.onMessage(message);
        RedisUtil redisUtil = applicationContext.getBean(RedisUtil.class);
        //接收数据解析
        JSONObject jsonObject = JSON.parseObject(message);
        RequestMessage requestMessage = new RequestMessage();
        requestMessage.setCourseId(jsonObject.getString("courseId"));
        requestMessage.setUserId(jsonObject.getString("userId"));
        requestMessage.setMessage(jsonObject.getString("message"));
        //处理返回数据
        Map<String, Session> courseClients = allClients.get(requestMessage.getCourseId());
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setMessage(requestMessage.getMessage());
        String name = (String) redisUtil.hget(requestMessage.getCourseId(), requestMessage.getUserId());
        responseMessage.setName(name);
        responseMessage.setCount(courseClients.size());
        String str = JSON.toJSONString(responseMessage);
        //发送消息

        for (Session session : courseClients.values()) {
            synchronized (session) {
                new Thread(() -> session.getAsyncRemote().sendText(str)).start();
            }
        }
        System.out.println(courseId + ":" + userId + ":" + str);
    }

    @OnError
    public void onError(Throwable t) {
        System.out.println(courseId + ":" + userId + ":" + t);
    }

    public void sendCount(){
        //处理返回数据
        Map<String, Session> courseClients = allClients.get(this.courseId);
        ResponseMessage responseMessage = new ResponseMessage();
//        responseMessage.setMessage(requestMessage.getMessage());
//        String name = (String) redisUtil.hget(requestMessage.getCourseId(), requestMessage.getUserId());
//        responseMessage.setName(name);
        responseMessage.setCount(courseClients.size());
        String str = JSON.toJSONString(responseMessage);
        //发送消息
        for (Session session : courseClients.values()) {
            synchronized (session) {
                new Thread(() -> session.getAsyncRemote().sendText(str)).start();
            }
        }
    }
}
